<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>前端路由实现</title>
    <style>
        .warp {
            width: 400px;
            height: 400px;
            border: 1px solid grey;
            margin: 0 auto;
        }
        
        .nav {
            border-bottom: 1px solid grey;
        }
        
        .nav li {
            display: inline-block;
            list-style: none;
        }
        
        .nav li a {
            display: inline-block;
            text-decoration: none;
            padding: 10px 15px;
        }
        
        .router {
            padding: 20px;
        }
        
        a {
            cursor: pointer;
        }
    </style>

</head>

<body>
    <section class="warp">
        <div class="nav">
            <ul>
                <li><a href="javascript:void(0)" data-path="index">首页</a></li>
                <li><a href="javascript:void(0)" data-path="news">新闻</a></li>
                <li><a href="javascript:void(0)" data-path="about">关于</a></li>
            </ul>
        </div>
        <div id="router" class="router">
            <!-- 内容加载区域 -->
        </div>
    </section>

    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script>
        (function() {

            var url = 'nav1';

            history.replaceState(url, null, ''); //最开始的状态，采用replace直接替换
            $('#router').html('<p>' + url + '</p>')

            $('a').on('click', function() {
                console.log(this.text)
                url = this.text;

                $('#router').html('<p>' + url + '</p>')
                history.pushState(url, null, '#/' + url);
            })
            window.addEventListener('popstate', function(e) {
                console.log(e.state);
                url = e.state
                $('#router').html('<p>' + url + '</p>')

            });
        })()
    </script>

</body>

</html>